<?php
	session_start();
	if(!isset($_SESSION["jara_admin"])) {
		header("Location: ../login.php");
		exit;
	}
	if($_SESSION["jara_permissions"][2] == 0) {	
		header("Location: error.php");
		exit;
	}
	require_once("../include/templating_fns.php");
	require_once("../include/db_fns.php");
	
	if(isset($_REQUEST["edit_action"])) {
		try {
			$template = $_POST["template"];
			if(!get_magic_quotes_gpc()) {
				$template = addslashes($template);
			}
			$query = "update jara_settings set value = '$template' where name = 'template'";
			$result = jara_db_query($query);
			if($result == 0) {
				$query = "insert into jara_settings values(NULL, 'template', '$template', 'Template')";
				jara_db_query($query);
				jara_page_start("Choose Template - Administrator CP");
				echo "<p>Changed template successfully.<br /><a href=\"index.php\">Return to Admin CP</a></p>";
				jara_page_end();
			}
			else {
				jara_page_start("Choose Template - Administrator CP");
				echo "<p>Changed template successfully.<br /><a href=\"index.php\">Return to Admin CP</a></p>";
				jara_page_end();
				exit;
			}
		}
		catch(JaraDatabaseException $ex) {
			jara_page_start("Choose Template - Administrator CP");
?>
	<p>
		A database error occured during the process of creating this page.
	</p>
	<p>
		Error type: <?php echo (($ex->getSqlStage() == 1) ? "MySQL connection error" : "MySQL query error"); ?><br />
		Error message: &quot;<?php echo $ex->getSqlMsg(); ?>&quot; [code <?php echo $ex->getSqlCode(); ?>]
	</p>
<?php
			jara_page_end();
			exit;
		}
		catch(JaraGeneralException $ex) {
			jara_page_start("Choose Template - Administrator CP");
?>
	<p>
		A general error occured during the process of creating this page.
	</p>
	<p>
		Error message: &quot;<?php echo $ex->getMessage(); ?>&quot;
	</p>
<?php
			jara_page_end();
			exit;
		}
		exit;
	}
	jara_page_start("Choose Template - Administrator CP");
	$templates = array();
	if (is_dir("../templates/")) {
		if ($dh = opendir("../templates/")) {
			while (($file = readdir($dh)) !== false) {
				if($file != "." && $file != "..") {
					array_push($templates, $file);
				}
			}
			closedir($dh);
		}
	}
?>
<form action="choose_template.php" method="post">
<p>
<input type="hidden" name="edit_action" id="edit_action" value="change" />
<h3>Choose Template</h3>
<p>
<img src="../templates/<?php echo $jconfig->template; ?>/meta.png" alt="Screenshot" id="sshot" /><br />
Choose an installed template: <select name="template" id="template"><?php foreach($templates as $template) { ?><option value="<?php echo $template; ?>"<?php if($template == $jconfig->template) { ?> selected="selected"<?php } ?> onclick="document.getElementById('sshot').src='../templates/<?php echo $template; ?>/meta.png'"><?php echo $template; ?></option><?php } ?></select>
</p>
<p>
<input type="submit" value="Save" />
</p>
</form>
<?php
	jara_page_end();
?>